using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Data;
using Core;
using System.Collections.Generic;

namespace MongoDBHelper
{
	public class MongoDBAPI
	{
		
		private MongoDatabase _db;
		private MongoServer _server;
		
		/// <summary>
		/// Connects the database.
		/// </summary>
		/// <returns>
		/// The database.
		/// </returns>
		/// <param name='ServerName'>
		/// Server name.
		/// </param>
		/// <param name='DatabaseName'>
		/// Database name.
		/// </param>
		public MongoDBAPI(string ServerName, string DatabaseName)
		{
			_server = MongoServer.Create (ServerName);// ("mongodb://localhost");
		     _db = _server.GetDatabase (DatabaseName);
			//return _db;
		}
		
		/// <summary>
		/// Saves the logs.
		/// </summary>
		/// <returns>
		/// The logs.
		/// </returns>
		/// <param name='appEvents'>
		/// If set to <c>true</c> app events.
		/// </param>
		public void SaveLogs(List<ApplicationEvent> appEvents)
		{
			
		    MongoCollection<BsonDocument> logContextEvents = _db.GetCollection<BsonDocument> ("LogContextEvents");                   
		     
		    logContextEvents.RemoveAll ();
		 
		 	foreach (ApplicationEvent appEvent in appEvents)
			{
		            		
				foreach (Context context in appEvent.Contexts)
				{
					logContextEvents.Save (new BsonDocument
			      {
			        {"Text", appEvent.Text},
			        {"Value", appEvent.ObjectValue},
					{"DateStamp", appEvent.DateStamp },
					{"ContextKey", context.Key },
					{"ContextValue", context.ContextValue}
			      });	
					
				}
				
			}	    
		}
		
		/// <summary>
		/// Saves the logs per second.
		/// </summary>
		/// <returns>
		/// The logs per second.
		/// </returns>
		/// <param name='appEvents'>
		/// If set to <c>true</c> app events.
		/// </param>
		public void SaveLogsPerSecond(List<ApplicationEvent> appEvents)
		{
			
		    MongoCollection<BsonDocument> logContextEventsPerSecond = _db.GetCollection<BsonDocument> ("LogContextEventsPerSecond");                   
		     
		    logContextEventsPerSecond.RemoveAll ();
		    
		 
		 	foreach (ApplicationEvent appEvent in appEvents)
			{
				DateTime convertedDate = Convert.ToDateTime(appEvent.DateStamp);
				BsonTimestamp convertedDateInSeconds = new BsonTimestamp(convertedDate.Second);
		        int iConvertedDateInSeconds = convertedDate.Second;
				
				
				
				foreach (Context context in appEvent.Contexts)
				{
					logContextEventsPerSecond.Save (new BsonDocument
			      {
			        {"Text", appEvent.Text},
			        {"Value", appEvent.ObjectValue},
					{"DateStamp",convertedDate},
					{"Seconds", iConvertedDateInSeconds },
					{"ContextKey", context.Key },
					{"ContextValue", context.ContextValue}
			      });	
					
				}
				
			}	    
		}
		
	}
	
	
	
	
}

